package com.ymatou.iapi.trading.operate.testcase;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.req.DeliveryValidationBean;
import com.ymatou.iapi.trading.operate.service.DeliveryValidationCall;
import com.ymatou.iapi.trading.operate.service.DeliveryValidationCall.JsonDeliveryValidationResult;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.YmtRefundWapper;
import com.ymttest.utils.constant.ECode;

/**
 * 发货效验 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_DeliveryValidation {
	private static DeliveryValidationBean deliveryvalidationbean;

	private static DeliveryValidationCall deliveryvalidationcall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("发货效验");
	}

	@Before
	public void caseUp() {
		deliveryvalidationbean = new DeliveryValidationBean();
		deliveryvalidationcall = new DeliveryValidationCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(deliveryvalidationcall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verifDb() {
		List<Integer> orderIds = new ArrayList<Integer>();
		DefaultWapper database = new DefaultWapper();
		orderIds = deliveryvalidationbean.getOrderIds();
		ArrayList<JsonDeliveryValidationResult> jsonResutlList = deliveryvalidationcall
				.getDeliveryValidationResults();
		// 多个订单，遍历每个订单
		if (orderIds.size() > 0) {
			for (int i = 0; i < orderIds.size(); i++) {
				Logger.comment("校验订单号:" + orderIds.get(i));
				// 订单主表
				List<Map> ymtOrders = database.selectOrderByOderId(orderIds
						.get(i));

				Logger.verifyEquals(jsonResutlList.get(i).getOrderId(),
						(Integer) ymtOrders.get(0).get("iOrderId"),
						"验证iOrderId");
				Logger.verifyEquals(jsonResutlList.get(i).getBuyerId(),
						(Integer) ymtOrders.get(0).get("iUserId"), "验证iUserId");
				String resultMsg = "";
				int orderStatus = (Integer) ymtOrders.get(0).get(
						"iTradingStatus");
				boolean isPaidInFull = (Boolean) ymtOrders.get(0).get(
						"bPaidInFull");

				Map map = new HashMap();
				map.put("orderId", deliveryvalidationbean.getOrderIds().get(0));

				int salesRefundStatus = 0;
				try {
					if ((new YmtRefundWapper().selectRefundBill(map)).size() > 0) {
						salesRefundStatus = new YmtRefundWapper()
								.selectRefundBill(map).get(0)
								.getSalesRefundStatus();
					}

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				boolean isCanDelivery = true;
				if (orderStatus != 17 || !isPaidInFull) {
					resultMsg = "当前订单状态不匹配";
					isCanDelivery = false;
				}
				if (salesRefundStatus == 1) {
					resultMsg = "当前订单正在退货退款中";
					isCanDelivery = false;
				}

				if (orderStatus == 3) {
					resultMsg = "当前订单已发货";
					isCanDelivery = false;
				}

				Logger.verifyEquals(isCanDelivery, jsonResutlList.get(i)
						.getIsCanDelivery(), "验证IsCanDelivery");
				Logger.verifyEquals(resultMsg, jsonResutlList.get(i)
						.getResultMsg(), "验证ResultMsg");
				Logger.verifyEquals((String) ymtOrders.get(0).get("sAddress"),
						jsonResutlList.get(i).getAddress(), "验证sAddress");
				Logger.verifyEquals(
						(String) ymtOrders.get(0).get("sReceivePerson"),
						jsonResutlList.get(i).getRecipient(),
						"验证sReceivePerson");
				Logger.verifyEquals((String) ymtOrders.get(0).get("sPhone"),
						jsonResutlList.get(i).getPhone(), "验证sPhone");
				Logger.verifyEquals(
						(String) ymtOrders.get(0).get("sTelephone"),
						jsonResutlList.get(i).getTelephone(), "验证sTelephone");
				Logger.verifyEquals((String) ymtOrders.get(0).get("sPostCode"),
						jsonResutlList.get(i).getPostCode(), "验证sPostCode");
				Logger.verifyEquals((String) ymtOrders.get(0).get("sEmail"),
						jsonResutlList.get(i).getEmail(), "验证sEmail");
			}
		} else {
			for (int i = 0; i < orderIds.size(); i++) {
				Logger.verifyEquals(jsonResutlList.get(i).getOrderId(),
						deliveryvalidationbean.getOrderIds().get(i),
						"验证iOrderId");
				Logger.verifyEquals(false, jsonResutlList.get(i)
						.getIsCanDelivery(), "验证IsCanDelivery");
				Logger.verifyEquals("此订单号不存在", jsonResutlList.get(i)
						.getResultMsg(), "验证ResultMsg");
				Logger.verifyEquals(-101,
						jsonResutlList.get(i).getResultCode(), "验证ResultMsg");
				Logger.verifyEquals(null, jsonResutlList.get(i).getAddress(),
						"验证sAddress");
				Logger.verifyEquals(null, jsonResutlList.get(i).getRecipient(),
						"验证sReceivePerson");
				Logger.verifyEquals(null, jsonResutlList.get(i).getPhone(),
						"验证sPhone");
				Logger.verifyEquals(null, jsonResutlList.get(i).getTelephone(),
						"验证sTelephone");
				Logger.verifyEquals(null, jsonResutlList.get(i).getPostCode(),
						"验证sPostCode");
				Logger.verifyEquals(null, jsonResutlList.get(i).getEmail(),
						"验证sEmail");
			}
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_DeliveryValidation_001() {
		Logger.start(true, "当前订单为已接单未发货状态,效验成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			OrderCallService orderService = new OrderCallService();
			PlaceOrderResp placeOrderResp = orderService.createM2cOrder();

			int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
			int userId = placeOrderResp.getUserId();
			int tradingId = placeOrderResp.getTradingId();

			BigDecimal totalPrice = placeOrderResp.getPayAmount();// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(orderId);
			// Logger.debug("orderIds:"+orderIds);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证code");
			verifDb();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_DeliveryValidation_002() {
		Logger.start(true, "订单状态为已发货,校验成功,返回结果正确");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			OrderCallService orderService = new OrderCallService();
			PlaceOrderResp placeOrderResp = orderService.createM2cOrder();

			int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
			int userId = placeOrderResp.getUserId();
			int tradingId = placeOrderResp.getTradingId();

			BigDecimal totalPrice = placeOrderResp.getPayAmount();// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			// 商家发货
			orderService.dispatched(orderId, sellerId);
			Logger.comment("前置数据准备结束");
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(orderId);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证Code");
			verifDb();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	public void Tc_DeliveryValidation_003() {
		Logger.start(true, "订单状态为买家补款未完成,校验成功,返回结果正确");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			OrderCallService orderService = new OrderCallService();
			Map map = orderService.appSaveOrder();
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			/*
			 * // 接单 orderService.acceptOrder(orderId, sellerId); // 商家发货 orderService.dispatched(orderId, sellerId);
			 */
			Logger.comment("前置数据准备结束");
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(orderId);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证Code");
			verifDb();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	public void Tc_DeliveryValidation_004() {
		Logger.start(true, "订单状态为买家补款完成待发货,校验成功,返回结果正确");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			OrderCallService orderService = new OrderCallService();
			Map map = orderService.appSaveOrder();
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			DecimalFormat df = new DecimalFormat("0.00");// 保留两位小数
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			// 卖家发起补款
			int price = 1 + new Random().nextInt(50);;
			BigDecimal payAmount = new BigDecimal(df.format(price));
			String postPayId = orderService.applyForPostPay(orderId, sellerId,
					payAmount);
			// 买家补款
			orderService.orderPostPayRequest(userId, payAmount, orderId);
			Logger.comment("前置数据准备结束");
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(orderId);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证Code");
			verifDb();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_DeliveryValidation_005() {
		Logger.start(true, "订单状态为退款退货中,校验成功,返回结果正确");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			OrderCallService orderService = new OrderCallService();
			PlaceOrderResp placeOrderResp = orderService.createM2cOrder();

			int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
			int userId = placeOrderResp.getUserId();
			int tradingId = placeOrderResp.getTradingId();

			BigDecimal totalPrice = placeOrderResp.getPayAmount();// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			//接单 
			orderService.acceptOrder(orderId, sellerId);
			// 退货退款同步
			orderService.applySalesRefundRequestInJava(orderId);
			Logger.comment("前置数据准备结束");
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(orderId);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证Code");
			verifDb();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_DeliveryValidation_006() {
		Logger.start(true, "多个订单号,有订单为不能发货状态,校验成功,返回结果正确");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			OrderCallService orderService = new OrderCallService();
			PlaceOrderResp placeOrderResp = orderService.createM2cOrder();

			int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
			int userId = placeOrderResp.getUserId();
			int tradingId = placeOrderResp.getTradingId();

			BigDecimal totalPrice = placeOrderResp.getPayAmount();// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			// 商家发货
			orderService.dispatched(orderId, sellerId);
			PlaceOrderResp placeOrderResp2 = orderService.createM2cOrder();

			int orderId2 = placeOrderResp2.getOrderList().get(0).getOrderId();
			int sellerId2 = placeOrderResp2.getOrderList().get(0).getSellerId();
			int userId2 = placeOrderResp2.getUserId();
			int tradingId2 = placeOrderResp2.getTradingId();

			BigDecimal totalPrice2 = placeOrderResp2.getPayAmount();// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId2, totalPrice2, tradingId2);
			// 接单
			orderService.acceptOrder(orderId2, sellerId2);
			Logger.comment("前置数据准备结束");
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(orderId);
			orderIds.add(orderId2);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证Code");
			verifDb();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_DeliveryValidation_007() {
		Logger.start(true, "请求的订单列表参数长度为0");
		try {
			List<Integer> orderIds = new ArrayList<Integer>();
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.FAILED400,
					deliveryvalidationcall.getString("code"), "验证Code");
			//Logger.verifyEquals(0, deliveryvalidationCall.getDeliveryValidationResults().size(), "请求的订单列表为0,返回结果为空");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_DeliveryValidation_008() {
		Logger.start(true, "订单list 为null");
		try {
			List<Integer> orderIds = new ArrayList<Integer>();
			// orderIds.add();
			// deliveryValidationBean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.FAILED400,
					deliveryvalidationcall.getString("code"), "验证Code");
			Logger.verifyEquals("orderIds:订单Id未提供",
					deliveryvalidationcall.getString("msg"), "验证Msg");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_DeliveryValidation_009() {
		Logger.start(true, "订单号不存在");
		try {
			List<Integer> orderIds = new ArrayList<Integer>();
			orderIds.add(11111111);
			orderIds.add(3);
			deliveryvalidationbean.setOrderIds(orderIds);
			deliveryvalidationcall.setData(deliveryvalidationbean);
			deliveryvalidationcall.callService();
			Logger.verifyEquals(ECode.SUCCESS,
					deliveryvalidationcall.getString("code"), "验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}